const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const session = require('koa-generic-session');
const redisStore = require('koa-redis');

// const { getRedis, setRedis, delRedis } = require('./cache/_redis.js');
const { REDIS_CONF } = require('./conf/db.js');
const { isDev, isProd } = require('./utils/env.js');

const indexViewRouter = require('./routes/index');
const userViewRouter = require('./routes/view/user.js');
const userAppRouter = require('./routes/api/user.js');
const errorViewRouter = require('./routes/view/error');

// error handler   接口出错--浏览器页面显示的报错信息
let onerrorConf = {};
if (isProd) {
  onerrorConf = {
    redirect: '/error'
  }
} 
onerror(app,onerrorConf)      

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

//session-作为koa的中间件(在路由注册之前) ctx.session
//session-与redis同步
app.keys=['Ab1_@']    //weibo.sid='加密字符串'
app.use(session({
  key:'weibo.sid',    //cookie name 默认为koa.sid
  prefix:'weibo:sess:',   //redis key的前缀, 默认是 ‘koa:sess:’  全名为weibo:sess:'加密字符串'
  cookie:{             //cookie设置 
    path:'/',          //每个接口都能 ctx.session
    httpOnly:true,     //禁止客户端修改cookie
    maxAge: 24 * 60 * 60 * 1000,   //cookie过期时长
    signed: true,        // signed为true时,必须设置app.keys加密     
  },
  ttl: 24 * 60 * 60 * 1000,        //redis过期时长(默认与cookie同步)
  store: redisStore({              //sessoin同步redis
    all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
  })
}))



// routes--注册
app.use(indexViewRouter.routes(), indexViewRouter.allowedMethods());
app.use(userViewRouter.routes(), userViewRouter.allowedMethods());
app.use(userAppRouter.routes(), userAppRouter.allowedMethods())
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods());    //404 *路由智能放在最后

//---------------redisClient
// getRedis('test2',(result) => {
//   console.log('test2:',result);
// })

//setRedis('test4',4);

//delRedis()

app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
